//
//  HUDView.swift
//  CustormHUD
//
//  Created by youmy on 2018/8/3.
//  Copyright © 2018年 youmy. All rights reserved.
//

import UIKit

enum HUDPosition {
    case top
    case center
    case bottom
}

class HUD: NSObject {
    
    static let shared:HUD = {
        let instance = HUD()
        return instance
    }()
    
    lazy var window:UIWindow = {
       return UIApplication.shared.windows.last!
    }()
    
    lazy var baseV:UIView = {
        let view = UIView(frame: UIScreen.main.bounds)
        let tapGR = UITapGestureRecognizer(target: self, action: #selector(remove(tapGesture:)))
//        view.addGestureRecognizer(tapGR)
        return view
    }()
    
    lazy var imageV:UIImageView = {
        let iv = UIImageView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
        iv.center = window.center
        return iv
    }()
    
    var activity:UIActivityIndicatorView?
    
    
    /// 提示文字
    ///
    /// - Parameters:
    ///   - text: 文字内容
    ///   - position: 文字位置
    ///   - second: 延时时间（默认1.5s）
    func showText(text:String,
                  bgColor:UIColor = UIColor(white: 0.3, alpha: 0.7),
                  foregroundColor:UIColor = .white,
                  position:HUDPosition = .center,
                  second:DispatchTime = .now() + 1.5){
        
        let label = UILabel()
        label.backgroundColor = bgColor
        label.textColor = foregroundColor
        label.font = UIFont.boldSystemFont(ofSize: 13)
        label.textAlignment = .center
        label.text = text
        label.sizeToFit()
        label.frame.size = CGSize(width: label.bounds.width + 15, height: label.bounds.height + 15)
        label.center = baseV.center
        
        switch position {
        case .top:
            label.center.y = 100
        case .center:
            label.center = baseV.center
        case .bottom:
            label.center.y = baseV.bounds.height - 100
        }
        
        label.layer.cornerRadius = 2
        label.layer.masksToBounds = true
        baseV.addSubview(label)
        window.addSubview(baseV)
        
        DispatchQueue.main.asyncAfter(deadline: second) {
            self.removeLoading()
        }
    }
    
    /// 加载动画
    ///
    /// - Parameter icon: gif图片名称
    func showGIFLoading(icon:String = "loading") {
        imageV.image = UIImage.gif(name: icon)
        baseV.addSubview(imageV)
        window.addSubview(baseV)
    }
 
    /// 加载提示
    ///
    /// - Parameters:
    ///   - background: 是否有背景色
    ///   - bgColor: 背景色
    ///   - foregroundColor: 前景色
    func showLoading(background:Bool = false,
                     bgColor:UIColor = UIColor(white: 0.3, alpha: 0.7),
                     foregroundColor:UIColor = .darkGray)
    {
        
        let activity = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
        
        activity.activityIndicatorViewStyle = .whiteLarge
        activity.center = baseV.center
        
        if background {
            activity.backgroundColor = bgColor
            activity.color = foregroundColor
            activity.layer.cornerRadius = 5
            activity.layer.masksToBounds = true
        }else{
            activity.center = baseV.center
            activity.color = foregroundColor
            window.addSubview(activity)
        }
        
        window.addSubview(activity)
        
        activity.startAnimating()
        self.activity = activity
    }
    
    
    /// 加载提示
    ///
    /// - Parameters:
    ///   - text: 提示文字
    ///   - bgColor: 背景色
    ///   - foregroundColor: 前景色
    func showLoadingText(text:String,
                         bgColor:UIColor = UIColor(white: 0.3, alpha: 0.7),
                         foregroundColor:UIColor = .white){
        
        window.addSubview(baseV)
        
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
        bgView.backgroundColor = bgColor
        bgView.layer.cornerRadius = 5
        bgView.layer.masksToBounds = true
        bgView.center = baseV.center
        baseV.addSubview(bgView)
        
        let activity = UIActivityIndicatorView()
        activity.activityIndicatorViewStyle = .whiteLarge
        activity.translatesAutoresizingMaskIntoConstraints = false
        activity.color = foregroundColor
        self.activity = activity
        activity.startAnimating()
        bgView.addSubview(activity)
        
        let contentLb = UILabel()
        contentLb.translatesAutoresizingMaskIntoConstraints = false
        contentLb.text = text
        contentLb.font = UIFont.boldSystemFont(ofSize: 13)
        contentLb.textColor = foregroundColor
        contentLb.sizeToFit()
        bgView.addSubview(contentLb)
        
        let views = ["activity":activity,"contentLb":contentLb] as [String : Any]
        
        let V = "V:|-15-[activity(==25)]-15-[contentLb]"
        let H = "[activity(==25)]"
        
        let constrainsV = NSLayoutConstraint.constraints(withVisualFormat: V, options: .alignAllCenterX, metrics: nil, views: views)
        let constraintH = NSLayoutConstraint.constraints(withVisualFormat: H, options: .init(rawValue: 0), metrics: nil, views: views)
        
        bgView.addConstraints(constrainsV)
        bgView.addConstraints(constraintH)
        
        bgView.addConstraint(NSLayoutConstraint.init(item: activity, attribute: .centerX, relatedBy: .equal, toItem: bgView, attribute: .centerX, multiplier: 1, constant: 0))
    }
    
    /// 加载提示
    ///
    /// - Parameters:
    ///   - image: 图片名称
    ///   - content: 提示文字
    ///   - bgColor: 弹窗背景
    func showResult(image:String, content:String, bgColor:UIColor = UIColor(white: 0.3, alpha: 0.7)){

        window.addSubview(baseV)
        
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
        bgView.backgroundColor = bgColor
        bgView.layer.cornerRadius = 5
        bgView.layer.masksToBounds = true
        bgView.center = baseV.center
        baseV.addSubview(bgView)
        
        let imageV = UIImageView()
        imageV.translatesAutoresizingMaskIntoConstraints = false
        imageV.image = UIImage(named: image)
        bgView.addSubview(imageV)
        
        let contentLb = UILabel()
        contentLb.translatesAutoresizingMaskIntoConstraints = false
        contentLb.text = content
        contentLb.font = UIFont.boldSystemFont(ofSize: 13)
        contentLb.textColor = .white
        contentLb.sizeToFit()
        bgView.addSubview(contentLb)
        
        let views = ["imageV":imageV,"contentLb":contentLb] as [String : Any]
        
        let V = "V:|-10-[imageV(==30)]-10-[contentLb]"
        let H = "[imageV(==30)]"
        
        let constrainsV = NSLayoutConstraint.constraints(withVisualFormat: V, options: .alignAllCenterX, metrics: nil, views: views)
        let constraintH = NSLayoutConstraint.constraints(withVisualFormat: H, options: .init(rawValue: 0), metrics: nil, views: views)
        
        bgView.addConstraints(constrainsV)
        bgView.addConstraints(constraintH)
        
        bgView.addConstraint(NSLayoutConstraint.init(item: imageV, attribute: .centerX, relatedBy: .equal, toItem: bgView, attribute: .centerX, multiplier: 1, constant: 0))
    }
    
    
    func removeLoading(){
        if (activity != nil) {
            activity?.stopAnimating()
        }
        removeAll(view: baseV)
        baseV.removeFromSuperview()
    }
    
    fileprivate func removeAll(view:UIView){
        for sub in view.subviews {
            sub.removeFromSuperview()
        }
    }
    
    @objc func remove(tapGesture:UITapGestureRecognizer){
        baseV.removeFromSuperview()
    }
}
